import requests
import json
import datetime
from config.configs import DATA_PATH
import os
import threading
import multiprocessing
from tools.funciton import write_xlsx, read_xlsx_file
from time import sleep

domain = 'https://stage.dingstock.net/xserver'
# domain = 'http://dc-oa-dev-0703.dingstock.net/xserver'
login_url = '{}/user/u/login'.format(domain)
add_box_url = '{}/20241111activity/activity/add/box'.format(domain)
open_box_url = '{}/20241111activity/activity/open'.format(domain)
shoecard_url = '{}/20241111activity/activity/user/shoecard'.format(domain)
set_actual_time_url = '{}/20241111activity/activity/time'.format(domain)
check_prize_url = '{}/20241111activity/activity/user/prize'.format(domain)
a = 921001
mobile_list = [a + i for i in range(400)]
RealPrizeIds = ["voucher500", "daogou7", "jinghuayou", "nikesock", "mrzhoushoe", "weiyi",
                "snkrsshoebag", "qiuxiebanhua", "chaoliutiezhi", "floormat", "qingxiji"]
add_box_header_dev = {
    "token": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InVkR3NLVFR1ZXciLCJyb2xlIjoidXNlciIsImlhdCI6MTcyNjY0MjUzMn0.6Wdq8-rqBp1T_owAfsBgfVqcm89LFmgLg1wAIW5PrKg"}
add_box_header_pre = {
    "token": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6InVyOVZ4cGxGdGkiLCJyb2xlIjoidXNlciIsImlhdCI6MTcyODg4OTM1NH0.NxYnOyHzg-LZ4DrQeuKrP-Zej-xer5xPRDwdUgB11CU"}


def get_token_userid(mobile):
    login_payload = json.dumps({
        "app": "iOS3.3.9(2024050901)",
        "deviceId": "704af491b4b1405eb2cd3c312b29ff58",
        "deviceToken": "f46cab65fb0abdfd61eecff773720c31c4b4597eb020e7a81e4819054cc1982a",
        "authData": {
            "sms": {
                "id": "+86{}".format(mobile),
                "code": "729514",
                "zone": "+86",
                "mobile": mobile
            }
        }
    })
    header = {
        'version': '3.3.9',
        'app': '',
        'Content-Type': 'application/json',
        'Accept': '*/*',
        'Connection': 'keep-alive'
    }
    login = requests.post(url=login_url, data=login_payload, headers=header)
    token = login.json()['res']['sessionToken']
    userid = login.json()['res']['id']
    isvip = login.json()['res']['isVip']
    return [token, userid, isvip]


def refresh_token():
    li = []
    for mo in mobile_list:
        li.append(get_token_userid(mo))
    write_xlsx(['token', 'userid', 'vip'], li, '盲盒活动token表')


file1 = os.path.join(DATA_PATH, '盲盒活动token表.xlsx')
token_list = read_xlsx_file(file1, 0)
userId_list = read_xlsx_file(file1, 1)
vips_list = read_xlsx_file(file1, 2)


# def open_box(num, activity_timestamp, days):
#     timestamp_list = [activity_timestamp]
#     for z in range(1, days):
#         time = datetime.datetime.fromtimestamp(activity_timestamp / 1000.0)
#         time += datetime.timedelta(days=z)
#         new_timestamp = int(time.timestamp() * 1000)
#         timestamp_list.append(new_timestamp)
#     for i in range(num):
#         mobile, token, userid, vip = mobile_list[i], token_list[i], userId_list[i], vips_list[i]
#         add_box_payload = {"userId": userid, "count": 100}
#         requests.get(url=add_box_url, headers=add_box_header, params=add_box_payload)
#         for actual_time in timestamp_list:
#             requests.post(url=set_actual_time_url, headers=add_box_header, data={"time": actual_time})
#             for d in range(5):
#                 res = requests.get(url=open_box_url, headers={"token": token})
#         print(f'第{i + 1}个用户：{mobile}，{userid}，开奖结束！')


def first_winning_user(num, level):
    """第一期活动开奖明细"""
    for i in range(num):
        mobile, token, userid, vip = mobile_list[i], token_list[i], userId_list[i], vips_list[i]
        result = requests.get(url=shoecard_url, headers={"token": token})
        print(result.json())
        user = result.json()['res']['ownCards']['firstPeriod']
        user_card_list = [i['number'] for i in user]
        user_card_list.reverse()
        prize_card_list = ['23', '5', '36', '16', '7', '8', '11']
        win_qty = 0
        for z in user_card_list:
            if z in prize_card_list:
                win_qty += 1
        if len(user_card_list) > 7:
            print(
                f'开奖规则有误，一个活动周期内，用户：{userid}，手机号：{mobile}，开出了{len(user_card_list)}张球鞋卡，抽卡结果：{user_card_list}')
        elif win_qty >= 5 and vip != True:
            print(
                f'开奖规则有误，非会员用户：{userid}，手机号：{mobile},开出了{(7 - win_qty)}等奖，抽卡结果：{user_card_list}')
        elif win_qty >= level:
            print(
                f'手机号：{mobile}中奖了！用户名：{userid}，中奖球鞋卡数量：{win_qty}，奖品等级：{7 - win_qty}，抽卡结果：{user_card_list}')
        else:
            print(f'手机号：{mobile}未中奖，用户名：{userid}，中奖球鞋卡数量：{win_qty}，抽卡结果：{user_card_list}')
        # li.append(7 - win_qty)


def second_winning_user(num, level):
    """第二期活动开奖明细"""
    for i in range(num):
        mobile, token, userid, vip = mobile_list[i], token_list[i], userId_list[i], vips_list[i]
        result = requests.get(url=shoecard_url, headers={"token": token})
        user = result.json()['res']['ownCards']['secondPeriod']
        user_card_list = [i['number'] for i in user]
        user_card_list.reverse()
        prize_card_list = ['2', '26', '10', '40', '38', '24', '18']
        win_qty = 0
        for z in user_card_list:
            if z in prize_card_list:
                win_qty += 1
        if len(user_card_list) > 7:
            print(
                f'开奖规则有误，一个活动周期内，用户：{userid}，手机号：{mobile}，开出了{len(user_card_list)}张球鞋卡，抽卡结果：{user_card_list}')
        elif win_qty >= 5 and vip != True:
            print(
                f'开奖规则有误，非会员用户：{userid}，手机号：{mobile},开出了{(7 - win_qty)}等奖，抽卡结果：{user_card_list}')
        elif win_qty >= level:
            print(
                f'中奖手机号：{mobile}，中奖用户：{userid}，中奖球鞋卡数量：{win_qty}，奖品等级：{7 - win_qty}，抽卡结果：{user_card_list}')
        else:
            print(f'手机号：{mobile}未中奖，用户名：{userid}中奖球鞋卡数量：{win_qty}，抽卡结果：{user_card_list}')


def third_winning_user(num, activity_timestamp, level):
    """第三期活动开奖明细"""
    for i in range(num):
        mobile, token, userid, vip = mobile_list[i], token_list[i], userId_list[i], vips_list[i]
        result = requests.get(url=shoecard_url, headers={"token": token})
        user = result.json()['res']['ownCards']['thirdPeriod']
        user_card_list = [i['number'] for i in user]
        user_card_list.reverse()
        prize_card_list = ['13', '17', '3', '1', '31', '6', '21']
        win_qty = 0
        for z in user_card_list:
            if z in prize_card_list:
                win_qty += 1
        if len(user_card_list) > 7:
            print(
                f'开奖规则有误，一个活动周期内，用户：{userid}，手机号：{mobile}，开出了{len(user_card_list)}张球鞋卡，抽卡结果：{user_card_list}')
        elif win_qty >= 5 and vip != True:
            print(
                f'开奖规则有误，非会员用户：{userid}，手机号：{mobile},开出了{(7 - win_qty)}等奖，抽卡结果：{user_card_list}')
        elif win_qty >= level:
            print(
                f'中奖手机号：{mobile}，中奖用户：{userid}，中奖球鞋卡数量：{win_qty}，奖品等级：{7 - win_qty}，抽卡结果：{user_card_list}')
        else:
            print(f'手机号：{mobile}未中奖，用户名：{userid}中奖球鞋卡数量：{win_qty}，抽卡结果：{user_card_list}')


def check_first_prize(mobile, token):
    """第一期实物奖品开奖结果"""
    payload = {"type": "openboxrecord"}
    prize_list = []
    result = requests.get(url=check_prize_url, params=payload, headers={"token": token}).json()['res']['prizes']
    for prize in result:
        if 'firstPeriod' in prize['id']:
            prize_list.append(prize['id'].split(':')[0])
    if set(prize_list) & set(RealPrizeIds):
        print('手机号：{}，实物奖品：{}'.format(mobile, str(set(prize_list) & set(RealPrizeIds))))
    else:
        print('未开出实物奖品')


def check_second_prize(mobile, token):
    """第二期实物奖品开奖结果"""
    payload = {"type": "openboxrecord"}
    prize_list = []
    result = requests.get(url=check_prize_url, params=payload, headers={"token": token}).json()['res']['prizes']
    for prize in result:
        if 'secondPeriod' in prize['id']:
            prize_list.append(prize['id'].split(':')[0])
    if set(prize_list) & set(RealPrizeIds):
        print('手机号：{}，实物奖品：{}'.format(mobile, str(set(prize_list) & set(RealPrizeIds))))
    else:
        print('未开出实物奖品')


def check_third_prize(mobile, token):
    """第三期实物奖品开奖结果"""
    payload = {"type": "openboxrecord"}
    prize_list = []
    result = requests.get(url=check_prize_url, params=payload, headers={"token": token}).json()['res']['prizes']
    for prize in result:
        if 'thirdPeriod' in prize['id']:
            prize_list.append(prize['id'].split(':')[0])
    if set(prize_list) & set(RealPrizeIds):
        print('手机号：{}，实物奖品：{}'.format(mobile, str(set(prize_list) & set(RealPrizeIds))))
    else:
        print('未开出实物奖品')


def open_box_for_user(i, activity_timestamp, days, header):
    """为单个用户执行开盒子任务的函数"""
    mobile, token, userid, vip = mobile_list[i], token_list[i], userId_list[i], vips_list[i]
    timestamp_list = [activity_timestamp]
    for z in range(1, days):
        time = datetime.datetime.fromtimestamp(activity_timestamp / 1000.0)
        time += datetime.timedelta(days=z)
        new_timestamp = int(time.timestamp() * 1000)
        timestamp_list.append(new_timestamp)
    requests.get(url=add_box_url, headers=header, params={"userId": userid, "count": 200})
    for actual_time in timestamp_list:
        requests.post(url=set_actual_time_url, headers=header, data={"time": actual_time})
        for d in range(10):
            res = requests.get(url=open_box_url, headers={"token": token})
    print(f'第{i + 1}个用户：{mobile}，{userid}，开奖结束！')


def open_boxes_multithreaded(num, activity_timestamp, days, header):
    threads = []
    for i in range(num):
        thread = threading.Thread(target=open_box_for_user, args=(i, activity_timestamp, days, header))
        threads.append(thread)
        thread.start()

    # 等待所有线程完成
    for thread in threads:
        thread.join()


def refresh_token_multithreaded(num):
    threads = []
    for i in range(num):
        thread = threading.Thread(target=refresh_token)
        threads.append(thread)
        thread.start()

    # 等待所有线程完成
    for thread in threads:
        thread.join()


# open_boxes_multithreaded(20, 1728903660000, 9)   ## 开200个用户的盲盒子，第一期活动，开奖周期为9天
# open_boxes_multithreaded(200, 1729789200000, 7)   ## 开200个用户的盲盒子，第二期活动，开奖周期为7天
# open_boxes_multithreaded(200, 1730394000000, 10, add_box_header_pre)   ## 开200个用户的盲盒子，第三期活动，开奖周期为10天
# first_winning_user(20,3)
# for i in range(200):
#     check_first_prize(mobile_list[i], token_list[i])
# second_winning_user(80,1716170400000,3)
# refresh_token_multithreaded(400)
